import * as fs from 'fs';
import * as path from 'path';
import { JavaParser } from '../utils/JavaParser.js';

export interface RefactorResult {
  success: boolean;
  message: string;
  filesModified: string[];
  errors?: string[];
}

export class FileRefactor {
  
  /**
   * 重命名Java类并更新所有引用
   */
  async renameClass(
    filePath: string, 
    oldClassName: string, 
    newClassName: string,
    projectPath: string
  ): Promise<RefactorResult> {
    const result: RefactorResult = {
      success: false,
      message: '',
      filesModified: [],
      errors: []
    };

    try {
      // 1. 重命名文件
      const newFilePath = this.generateNewFilePath(filePath, oldClassName, newClassName);
      if (fs.existsSync(newFilePath)) {
        result.errors?.push(`目标文件已存在: ${newFilePath}`);
        return result;
      }

      // 2. 更新文件内容中的类名
      const fileContent = fs.readFileSync(filePath, 'utf-8');
      const updatedContent = this.replaceClassName(fileContent, oldClassName, newClassName);
      
      // 3. 写入新文件
      fs.writeFileSync(newFilePath, updatedContent);
      result.filesModified.push(newFilePath);

      // 4. 查找并更新所有引用此类的文件
      const referencingFiles = await this.findReferencingFiles(oldClassName, projectPath);
      for (const refFile of referencingFiles) {
        if (refFile !== filePath) { // 不处理原文件，因为已经重命名了
          await this.updateReferencesInFile(refFile, oldClassName, newClassName);
          result.filesModified.push(refFile);
        }
      }

      // 5. 删除原文件
      fs.unlinkSync(filePath);

      result.success = true;
      result.message = `成功重命名类 ${oldClassName} -> ${newClassName}，更新了 ${result.filesModified.length} 个文件`;
      
    } catch (error) {
      result.errors?.push(`重命名失败: ${error}`);
      result.message = `重命名类失败: ${error}`;
    }

    return result;
  }

  /**
   * 重命名方法并更新所有调用
   */
  async renameMethod(
    filePath: string,
    className: string,
    oldMethodName: string,
    newMethodName: string,
    projectPath: string
  ): Promise<RefactorResult> {
    const result: RefactorResult = {
      success: false,
      message: '',
      filesModified: [],
      errors: []
    };

    try {
      // 1. 更新方法定义
      const fileContent = fs.readFileSync(filePath, 'utf-8');
      const updatedContent = this.replaceMethodName(fileContent, oldMethodName, newMethodName);
      fs.writeFileSync(filePath, updatedContent);
      result.filesModified.push(filePath);

      // 2. 查找并更新所有调用此方法的文件
      const referencingFiles = await this.findMethodReferences(className, oldMethodName, projectPath);
      for (const refFile of referencingFiles) {
        if (refFile !== filePath) {
          await this.updateMethodCallsInFile(refFile, className, oldMethodName, newMethodName);
          result.filesModified.push(refFile);
        }
      }

      result.success = true;
      result.message = `成功重命名方法 ${oldMethodName} -> ${newMethodName}，更新了 ${result.filesModified.length} 个文件`;

    } catch (error) {
      result.errors?.push(`重命名方法失败: ${error}`);
      result.message = `重命名方法失败: ${error}`;
    }

    return result;
  }

  /**
   * 提取方法重构
   */
  async extractMethod(
    filePath: string,
    startLine: number,
    endLine: number,
    newMethodName: string,
    returnType?: string
  ): Promise<RefactorResult> {
    const result: RefactorResult = {
      success: false,
      message: '',
      filesModified: [],
      errors: []
    };

    try {
      console.error(`[extractMethod] 开始提取方法: ${newMethodName}, 行 ${startLine}-${endLine}`);
      
      const fileContent = fs.readFileSync(filePath, 'utf-8');
      const lines = fileContent.split('\n');

      // 1. 提取要抽取的代码
      const extractedLines = lines.slice(startLine - 1, endLine);
      const extractedCode = extractedLines.join('\n');
      
      console.error(`[extractMethod] 提取的代码:\n${extractedCode}`);
      
      // 2. 使用新的JavaParser分析变量依赖
      const dependencies = JavaParser.analyzeVariableDependencies(fileContent, startLine, endLine);
      
      // 3. 检查是否有多个变量需要返回
      if (dependencies.returnNeeded.size > 1) {
        result.errors?.push(`无法提取：有 ${dependencies.returnNeeded.size} 个变量需要返回，Java不支持多返回值`);
        result.message = `提取失败：需要返回多个变量（${Array.from(dependencies.returnNeeded.keys()).join(', ')}）`;
        return result;
      }
      
      // 4. 生成新方法 - 使用新的格式
      const newMethod = this.generateNewMethodV2(
        newMethodName, 
        extractedCode, 
        dependencies, 
        returnType
      );
      
      console.error(`[extractMethod] 生成的新方法:\n${newMethod}`);

      // 5. 生成替换代码 - 使用新的格式
      const replacement = this.generateReplacementV2(newMethodName, dependencies);
      
      console.error(`[extractMethod] 替换代码:\n${replacement.join('\n')}`);
      
      // 6. 替换原代码
      lines.splice(startLine - 1, endLine - startLine + 1, ...replacement);

      // 7. 插入新方法到合适位置
      const insertIndex = this.findMethodInsertPosition(lines);
      lines.splice(insertIndex, 0, '', newMethod, '');

      // 8. 写回文件
      fs.writeFileSync(filePath, lines.join('\n'));
      result.filesModified.push(filePath);

      result.success = true;
      result.message = `成功提取方法 ${newMethodName}`;
      
      console.error(`[extractMethod] 提取成功`);

    } catch (error) {
      result.errors?.push(`提取方法失败: ${error}`);
      result.message = `提取方法失败: ${error}`;
      console.error(`[extractMethod] 提取失败:`, error);
    }

    return result;
  }

  /**
   * 自动重构大方法
   */
  async autoRefactorLargeMethod(
    filePath: string,
    methodName: string,
    maxLines: number = 80
  ): Promise<RefactorResult> {
    // 🛡️ 强制安全返回 - 完全禁用自动修改功能
    console.error(`[autoRefactorLargeMethod] 🛡️ 安全模式激活 - 禁止任何自动修改`);
    
    const result: RefactorResult = {
      success: true,
      message: '🛡️ 安全模式：auto_refactor_large_method已完全禁用\n\n' +
               '❌ 自动修改功能已永久禁用以保护代码安全\n' +
               '✅ 请使用extract_method工具进行手动重构\n' +
               '📋 建议：先用analyze_java_file分析文件结构\n\n' +
               '💡 手动重构步骤：\n' +
               '1. 运行 analyze_java_file 分析文件\n' +
               '2. 识别可提取的代码块\n' +
               '3. 使用 extract_method 逐一提取\n' +
               '4. 为新方法选择合适的名称\n\n' +
               '🚨 重要：此功能已禁用，不会修改任何文件',
      filesModified: [],
      errors: []
    };
    
    console.error(`[autoRefactorLargeMethod] 🚫 已阻止潜在的文件修改操作`);
    return result;

  }

  // 私有辅助方法
  private generateNewFilePath(oldPath: string, oldClassName: string, newClassName: string): string {
    const dir = path.dirname(oldPath);
    const ext = path.extname(oldPath);
    return path.join(dir, `${newClassName}${ext}`);
  }
  
  /**
   * 生成新的提取方法 - V2版本，适配新的JavaParser输出
   */
  private generateNewMethodV2(
    methodName: string,
    extractedCode: string,
    dependencies: {
      declaredBefore: Map<string, { type: string, line: number }>,
      declaredInside: Map<string, { type: string, line: number }>,
      usedInside: Set<string>,
      usedAfter: Map<string, Set<number>>,
      parameters: Map<string, string>,
      returnNeeded: Map<string, string>
    },
    explicitReturnType?: string
  ): string {
    // 确定返回类型
    let returnType = 'void';
    let returnVarName = '';
    
    if (dependencies.returnNeeded.size === 1) {
      const [varName, varType] = Array.from(dependencies.returnNeeded.entries())[0];
      returnType = varType;
      returnVarName = varName;
    } else if (explicitReturnType) {
      returnType = explicitReturnType;
    }
    
    // 生成参数列表
    const params = Array.from(dependencies.parameters.entries())
      .map(([name, type]) => `${type} ${name}`)
      .join(', ');
    
    // 处理提取的代码
    let methodBody = extractedCode;
    
    // 如果需要返回值，添加return语句
    if (returnVarName && returnType !== 'void') {
      const lines = methodBody.split('\n');
      const lastNonEmptyLine = lines.filter(l => l.trim()).pop();
      
      // 检查最后一行是否已经是return语句
      if (lastNonEmptyLine && !lastNonEmptyLine.trim().startsWith('return')) {
        methodBody += `\n        return ${returnVarName};`;
      }
    }
    
    // 格式化方法体缩进
    const formattedBody = methodBody.split('\n')
      .map(line => line.trim() ? '        ' + line.trim() : '')
      .join('\n');
    
    return `    private ${returnType} ${methodName}(${params}) {\n${formattedBody}\n    }`;
  }

  /**
   * 生成新的提取方法 - 旧版本，保持兼容性
   */
  private generateNewMethod(
    methodName: string,
    extractedCode: string,
    dependencies: {
      parameters: Map<string, string>,
      returnNeeded: Map<string, string>
    },
    explicitReturnType?: string
  ): string {
    // 确定返回类型
    let returnType = 'void';
    let returnVarName = '';
    
    if (dependencies.returnNeeded.size === 1) {
      const [varName, varType] = Array.from(dependencies.returnNeeded.entries())[0];
      returnType = varType;
      returnVarName = varName;
    } else if (explicitReturnType) {
      returnType = explicitReturnType;
    }
    
    // 生成参数列表
    const params = Array.from(dependencies.parameters.entries())
      .map(([name, type]) => `${type} ${name}`)
      .join(', ');
    
    // 处理提取的代码
    let methodBody = extractedCode;
    
    // 如果需要返回值，添加return语句
    if (returnVarName && returnType !== 'void') {
      const lines = methodBody.split('\n');
      const lastNonEmptyLine = lines.filter(l => l.trim()).pop();
      
      // 检查最后一行是否已经是return语句
      if (lastNonEmptyLine && !lastNonEmptyLine.trim().startsWith('return')) {
        methodBody += `\n        return ${returnVarName};`;
      }
    }
    
    // 格式化方法体缩进
    const formattedBody = methodBody.split('\n')
      .map(line => line.trim() ? '        ' + line.trim() : '')
      .join('\n');
    
    return `    private ${returnType} ${methodName}(${params}) {\n${formattedBody}\n    }`;
  }
  
  /**
   * 生成替换代码 - V2版本，适配新的JavaParser输出
   */
  private generateReplacementV2(
    methodName: string,
    dependencies: {
      declaredBefore: Map<string, { type: string, line: number }>,
      declaredInside: Map<string, { type: string, line: number }>,
      usedInside: Set<string>,
      usedAfter: Map<string, Set<number>>,
      parameters: Map<string, string>,
      returnNeeded: Map<string, string>
    }
  ): string[] {
    const replacement: string[] = [];
    
    // 1. 生成方法调用
    const params = Array.from(dependencies.parameters.keys()).join(', ');
    
    if (dependencies.returnNeeded.size === 1) {
      const [varName, varType] = Array.from(dependencies.returnNeeded.entries())[0];
      // 声明并赋值返回变量
      replacement.push(`        ${varType} ${varName} = ${methodName}(${params});`);
    } else if (dependencies.returnNeeded.size === 0) {
      replacement.push(`        ${methodName}(${params});`);
    } else {
      // 多个返回值的情况，不应该到这里（已在前面检查）
      replacement.push(`        // 错误：多个返回值，Java不支持`);
      replacement.push(`        ${methodName}(${params});`);
    }
    
    return replacement;
  }

  /**
   * 生成替换代码 - 旧版本，保持兼容性
   */
  private generateReplacement(
    methodName: string,
    dependencies: {
      parameters: Map<string, string>,
      returnNeeded: Map<string, string>,
      declaredInside: Map<string, { type: string, line: number }>,
      usedAfter: Map<string, Set<number>>
    }
  ): string[] {
    const replacement: string[] = [];
    
    // 1. 为后续需要使用的变量生成声明
    for (const [varName] of dependencies.usedAfter) {
      if (dependencies.declaredInside.has(varName)) {
        const varInfo = dependencies.declaredInside.get(varName)!;
        replacement.push(`        ${varInfo.type} ${varName};`);
      }
    }
    
    // 2. 生成方法调用
    const params = Array.from(dependencies.parameters.keys()).join(', ');
    
    if (dependencies.returnNeeded.size === 1) {
      const [varName] = Array.from(dependencies.returnNeeded.keys());
      replacement.push(`        ${varName} = ${methodName}(${params});`);
    } else {
      replacement.push(`        ${methodName}(${params});`);
    }
    
    return replacement;
  }

  private replaceClassName(content: string, oldName: string, newName: string): string {
    // 替换类声明
    content = content.replace(
      new RegExp(`\\bclass\\s+${oldName}\\b`, 'g'),
      `class ${newName}`
    );
    
    // 替换构造函数
    content = content.replace(
      new RegExp(`\\b${oldName}\\s*\\(`, 'g'),
      `${newName}(`
    );

    return content;
  }

  private async findReferencingFiles(className: string, projectPath: string): Promise<string[]> {
    const javaFiles: string[] = [];
    
    const scanDirectory = (dir: string) => {
      const items = fs.readdirSync(dir);
      for (const item of items) {
        const fullPath = path.join(dir, item);
        const stat = fs.statSync(fullPath);
        
        if (stat.isDirectory() && !item.startsWith('.')) {
          scanDirectory(fullPath);
        } else if (item.endsWith('.java')) {
          const content = fs.readFileSync(fullPath, 'utf-8');
          if (content.includes(className)) {
            javaFiles.push(fullPath);
          }
        }
      }
    };

    scanDirectory(projectPath);
    return javaFiles;
  }

  private async updateReferencesInFile(filePath: string, oldName: string, newName: string): Promise<void> {
    const content = fs.readFileSync(filePath, 'utf-8');
    
    // 更新import语句
    let updatedContent = content.replace(
      new RegExp(`\\bimport\\s+.*\\.${oldName}\\b`, 'g'),
      match => match.replace(oldName, newName)
    );

    // 更新类型引用（包括变量声明和构造函数调用）
    updatedContent = updatedContent.replace(
      new RegExp(`\\b${oldName}\\b`, 'g'),
      newName
    );

    // 额外确保构造函数调用被更新
    updatedContent = updatedContent.replace(
      new RegExp(`new\\s+${oldName}\\s*\\(`, 'g'),
      `new ${newName}(`
    );

    fs.writeFileSync(filePath, updatedContent);
  }

  private replaceMethodName(content: string, oldName: string, newName: string): string {
    // 替换方法定义
    return content.replace(
      new RegExp(`\\b${oldName}\\s*\\(`, 'g'),
      `${newName}(`
    );
  }

  private async findMethodReferences(className: string, methodName: string, projectPath: string): Promise<string[]> {
    const referencingFiles: string[] = [];
    
    const scanDirectory = (dir: string) => {
      const items = fs.readdirSync(dir);
      for (const item of items) {
        const fullPath = path.join(dir, item);
        const stat = fs.statSync(fullPath);
        
        if (stat.isDirectory() && !item.startsWith('.')) {
          scanDirectory(fullPath);
        } else if (item.endsWith('.java')) {
          const content = fs.readFileSync(fullPath, 'utf-8');
          if (content.includes(`${methodName}(`)) {
            referencingFiles.push(fullPath);
          }
        }
      }
    };

    scanDirectory(projectPath);
    return referencingFiles;
  }

  private async updateMethodCallsInFile(
    filePath: string, 
    className: string, 
    oldMethodName: string, 
    newMethodName: string
  ): Promise<void> {
    const content = fs.readFileSync(filePath, 'utf-8');
    
    // 更新方法调用
    const updatedContent = content.replace(
      new RegExp(`\\b${oldMethodName}\\s*\\(`, 'g'),
      `${newMethodName}(`
    );

    fs.writeFileSync(filePath, updatedContent);
  }

  /**
   * 分析提取代码的变量作用域 - 完全重写版本
   */
  private analyzeExtractedCodeScope(extractedCode: string, fullFileContent: string, startLine: number, endLine: number): { 
    parameters: string[], 
    returnValue?: string,
    parameterTypes: Map<string, string>,
    declaredVariables: Map<string, string>,
    usedVariablesAfter: Set<string>,
    needToReturnVars: Set<string>
  } {
    const parameters: string[] = [];
    const parameterTypes = new Map<string, string>();
    const declaredVariables = new Map<string, string>();
    const usedVariablesAfter = new Set<string>();
    const needToReturnVars = new Set<string>();
    const lines = fullFileContent.split('\n');
    
    // 1. 首先分析整个方法的上下文
    const methodBounds = this.findMethodBounds(fullFileContent, this.extractMethodName(fullFileContent, startLine));
    if (!methodBounds) {
      throw new Error('无法找到方法边界');
    }
    
    // 2. 收集方法中所有变量声明（不包括提取的代码段）
    const allMethodVariables = new Map<string, {type: string, line: number}>();
    for (let i = methodBounds.startLine - 1; i < methodBounds.endLine; i++) {
      // 跳过提取的代码段
      if (i >= startLine - 1 && i < endLine) {
        continue;
      }
      
      const line = lines[i];
      // 更全面的变量声明匹配
      const patterns = [
        /\b(\w+(?:<[^>]*>)?)\s+(\w+)\s*=\s*([^;]+);/g,  // Type var = value;
        /\b(\w+(?:<[^>]*>)?)\s+(\w+)\s*;/g,              // Type var;
        /for\s*\(\s*(\w+(?:<[^>]*>)?)\s+(\w+)\s*:/g,     // for (Type var : ...)
        /catch\s*\(\s*(\w+(?:<[^>]*>)?)\s+(\w+)\s*\)/g   // catch (Exception e)
      ];
      
      for (const pattern of patterns) {
        let match;
        while ((match = pattern.exec(line)) !== null) {
          const varType = match[1];
          const varName = match[2];
          if (!this.isJavaKeywordOrBuiltin(varType)) {
            allMethodVariables.set(varName, {type: varType, line: i});
          }
        }
      }
    }
    
    // 3. 分析提取代码中声明的变量
    const extractedLines = extractedCode.split('\n');
    const extractedDeclaredVars = new Map<string, string>();
    
    for (const line of extractedLines) {
      const patterns = [
        /\b(\w+(?:<[^>]*>)?)\s+(\w+)\s*=\s*([^;]+);/g,
        /\b(\w+(?:<[^>]*>)?)\s+(\w+)\s*;/g
      ];
      
      for (const pattern of patterns) {
        let match;
        while ((match = pattern.exec(line)) !== null) {
          const varType = match[1];
          const varName = match[2];
          if (!this.isJavaKeywordOrBuiltin(varType)) {
            extractedDeclaredVars.set(varName, varType);
            declaredVariables.set(varName, varType);
          }
        }
      }
    }
    
    // 4. 分析提取代码中使用的变量
    const usedInExtracted = new Set<string>();
    const variableUsagePattern = /\b([a-zA-Z_$][a-zA-Z0-9_$]*)\b/g;
    let match;
    
    while ((match = variableUsagePattern.exec(extractedCode)) !== null) {
      const varName = match[1];
      if (!this.isJavaKeywordOrBuiltin(varName)) {
        usedInExtracted.add(varName);
      }
    }
    
    // 5. 分析提取代码后面对变量的使用
    for (let i = endLine; i < methodBounds.endLine; i++) {
      const line = lines[i];
      
      // 检查提取代码中声明的变量是否在后面被使用
      for (const [varName] of extractedDeclaredVars) {
        // 使用更精确的匹配，避免子字符串匹配
        const varUsageRegex = new RegExp(`\\b${varName}\\b`);
        if (varUsageRegex.test(line)) {
          usedVariablesAfter.add(varName);
          needToReturnVars.add(varName);
        }
      }
    }
    
    // 6. 分析类的成员变量
    const memberFields = this.findMemberFields(fullFileContent);
    
    // 7. 确定需要作为参数传递的变量
    for (const varName of usedInExtracted) {
      // 如果变量在提取代码中使用但未在其中声明
      if (!extractedDeclaredVars.has(varName)) {
        // 检查是否是方法中的变量（不是成员变量）
        if (allMethodVariables.has(varName) && !memberFields.has(varName)) {
          const varInfo = allMethodVariables.get(varName)!;
          // 只有在提取代码之前声明的变量才需要作为参数
          if (varInfo.line < startLine - 1) {
            parameters.push(varName);
            parameterTypes.set(varName, varInfo.type);
          }
        } else if (!memberFields.has(varName) && !this.isJavaKeywordOrBuiltin(varName)) {
          // 如果在提取代码之前的行中有声明，也要作为参数
          for (let i = 0; i < startLine - 1; i++) {
            const line = lines[i];
            const varDeclPattern = new RegExp(`\\b(\\w+(?:<[^>]*>)?)\\s+${varName}\\s*[=;]`);
            const match = varDeclPattern.exec(line);
            if (match) {
              parameters.push(varName);
              parameterTypes.set(varName, match[1]);
              break;
            }
          }
        }
      }
    }
    
    // 8. 分析返回值
    let returnValue = this.analyzeReturnValue(extractedCode);
    
    // 如果有变量在后面需要使用，优先返回这些变量
    if (needToReturnVars.size > 0 && !returnValue) {
      // 如果只有一个变量需要返回
      if (needToReturnVars.size === 1) {
        const varName = Array.from(needToReturnVars)[0];
        returnValue = extractedDeclaredVars.get(varName);
      } else {
        // TODO: 处理多个返回值的情况（可能需要创建包装类）
        console.warn('需要返回多个变量，当前只支持返回第一个');
        const varName = Array.from(needToReturnVars)[0];
        returnValue = extractedDeclaredVars.get(varName);
      }
    }
    
    return { 
      parameters, 
      returnValue, 
      parameterTypes, 
      declaredVariables: extractedDeclaredVars,
      usedVariablesAfter,
      needToReturnVars
    };
  }
  
  private isJavaKeywordOrBuiltin(word: string): boolean {
    const keywords = [
      'abstract', 'assert', 'boolean', 'break', 'byte', 'case', 'catch', 'char',
      'class', 'const', 'continue', 'default', 'do', 'double', 'else', 'enum',
      'extends', 'final', 'finally', 'float', 'for', 'goto', 'if', 'implements',
      'import', 'instanceof', 'int', 'interface', 'long', 'native', 'new', 'null',
      'package', 'private', 'protected', 'public', 'return', 'short', 'static',
      'strictfp', 'super', 'switch', 'synchronized', 'this', 'throw', 'throws',
      'transient', 'try', 'void', 'volatile', 'while', 'true', 'false',
      'String', 'Object', 'System', 'List', 'Map', 'Set', 'Collection'
    ];
    return keywords.includes(word);
  }
  
  private extractMethodName(content: string, startLine: number): string {
    const lines = content.split('\n');
    if (startLine > 0 && startLine <= lines.length) {
      const line = lines[startLine - 1];
      const methodMatch = line.match(/\s*(?:public|private|protected)?\s*(?:static)?\s*\w+\s+(\w+)\s*\(/);
      return methodMatch ? methodMatch[1] : 'unknownMethod';
    }
    return 'unknownMethod';
  }
  
  private inferVariableType(varName: string, content: string): string {
    // 尝试在代码中找到变量的类型声明
    const declPattern = new RegExp(`\\b(\\w+(?:<[^>]*>)?)\\s+${varName}\\s*[=;]`);
    const match = declPattern.exec(content);
    
    if (match) {
      return match[1];
    }
    
    // 根据变量名模式推断
    if (varName.toLowerCase().includes('list')) return 'List<Object>';
    if (varName.toLowerCase().includes('map')) return 'Map<String, Object>';
    if (varName.toLowerCase().includes('set')) return 'Set<Object>';
    if (varName.toLowerCase().includes('id')) return 'String';
    if (varName.toLowerCase().includes('count') || varName.toLowerCase().includes('size')) return 'int';
    if (varName.toLowerCase().includes('flag') || varName.toLowerCase().includes('is')) return 'boolean';
    
    return 'Object'; // 默认类型
  }
  
  private analyzeReturnValue(code: string): string | undefined {
    // 检查是否有return语句
    if (code.includes('return ')) {
      const returnMatch = code.match(/return\s+([^;]+);/);
      if (returnMatch) {
        const returnExpr = returnMatch[1].trim();
        
        // 简单类型推断
        if (returnExpr === 'true' || returnExpr === 'false') return 'boolean';
        if (/^\d+$/.test(returnExpr)) return 'int';
        if (/^\d+\.\d+$/.test(returnExpr)) return 'double';
        if (returnExpr.startsWith('"') && returnExpr.endsWith('"')) return 'String';
        if (returnExpr === 'null') return 'Object';
        
        return 'Object'; // 复杂表达式默认为Object
      }
    }
    
    return undefined; // void方法
  }

  private generateExtractedMethod(
    methodName: string, 
    code: string, 
    analysis: { 
      parameters: string[], 
      returnValue?: string, 
      parameterTypes: Map<string, string>,
      declaredVariables: Map<string, string>,
      usedVariablesAfter: Set<string>,
      needToReturnVars: Set<string>
    },
    returnType?: string
  ): string {
    // 生成带类型的参数列表
    const params = analysis.parameters.map(param => {
      const type = analysis.parameterTypes.get(param) || 'Object';
      return `${type} ${param}`;
    }).join(', ');
    
    // 确定返回类型
    let rt = returnType || analysis.returnValue || 'void';
    
    // 如果有变量在提取后还要使用，需要返回这些变量
    if (analysis.needToReturnVars.size > 0 && !returnType && !analysis.returnValue) {
      const firstVar = Array.from(analysis.needToReturnVars)[0];
      rt = analysis.declaredVariables.get(firstVar) || 'Object';
    }
    
    if (!this.isValidJavaType(rt)) {
      rt = 'void';
    }
    
    // 清理和格式化代码
    let cleanedCode = this.cleanAndFormatCode(code);
    
    // 如果需要返回变量，在代码末尾添加return语句
    if (analysis.needToReturnVars.size > 0 && rt !== 'void') {
      const returnVar = Array.from(analysis.needToReturnVars)[0];
      // 确保添加return语句（如果代码中还没有return语句）
      if (!cleanedCode.includes(`return ${returnVar}`)) {
        cleanedCode = cleanedCode.trim();
        if (!cleanedCode.endsWith(';')) {
          cleanedCode += ';';
        }
        cleanedCode += `\n        return ${returnVar};`;
      }
    }
    
    return `    private ${rt} ${methodName}(${params}) {
${cleanedCode}
    }`;
  }

  private generateMethodCall(methodName: string, parameters: string[], returnValue?: string): string {
    const params = parameters.join(', ');
    
    if (returnValue && returnValue !== 'void' && this.isValidJavaType(returnValue)) {
      // 如果有返回值，需要接收返回值
      return `        ${returnValue} result = ${methodName}(${params});`;
    } else {
      return `        ${methodName}(${params});`;
    }
  }

  private findMethodInsertPosition(lines: string[]): number {
    // 找到主类的结束位置，在其中插入新方法
    let classLevel = 0;
    let inMainClass = false;
    let lastMethodEndLine = -1;
    
    for (let i = 0; i < lines.length; i++) {
      const line = lines[i].trim();
      
      // 检测类的开始
      if (line.includes('class ') && line.includes('{')) {
        if (!inMainClass) {
          inMainClass = true;
          classLevel = 1;
        }
        continue;
      }
      
      if (inMainClass) {
        // 计算大括号层级
        for (const char of line) {
          if (char === '{') {
            classLevel++;
          } else if (char === '}') {
            classLevel--;
            
            // 如果回到类的层级1，说明这是一个方法或内部结构的结束
            if (classLevel === 1) {
              lastMethodEndLine = i;
            }
            // 如果回到层级0，说明主类结束
            else if (classLevel === 0) {
              // 如果有找到方法结束位置，在那里插入；否则在类结束前插入
              return lastMethodEndLine > 0 ? lastMethodEndLine + 1 : i;
            }
          }
        }
      }
    }
    
    // 如果没有找到合适位置，返回倒数第二行（避免插入到文件最后一行）
    return Math.max(0, lines.length - 2);
  }

  private findMethodBounds(content: string, methodName: string): { startLine: number, endLine: number } | null {
    const lines = content.split('\n');
    
    for (let i = 0; i < lines.length; i++) {
      const line = lines[i];
      
      // 更精确的方法匹配：确保匹配的是方法声明而不是方法调用
      const methodRegex = new RegExp(`\\s*(public|private|protected)?\\s*(static)?\\s*\\w+\\s+${methodName}\\s*\\([^)]*\\)\\s*(\\{|throws)`);
      if (methodRegex.test(line)) {
        const methodStartLine = i + 1; // 1-based
        
        // 找到方法的第一个开大括号
        let firstBraceLineIndex = i;
        let foundOpenBrace = false;
        for (let k = i; k < lines.length; k++) {
          if (lines[k].includes('{')) {
            firstBraceLineIndex = k;
            foundOpenBrace = true;
            break;
          }
        }
        
        if (!foundOpenBrace) {
          // 抽象方法或接口方法
          for (let k = i; k < lines.length; k++) {
            if (lines[k].trim().endsWith(';')) {
              return { startLine: methodStartLine, endLine: k + 1 };
            }
          }
        }
        
        // 从方法体开始计算大括号平衡
        let braceCount = 0;
        for (let j = firstBraceLineIndex; j < lines.length; j++) {
          const currentLine = lines[j];
          
          // 移除字符串中的括号以避免误计算
          const cleanedLine = this.removeStringContent(currentLine);
          
          for (const char of cleanedLine) {
            if (char === '{') {
              braceCount++;
            } else if (char === '}') {
              braceCount--;
              
              if (braceCount === 0) {
                return { startLine: methodStartLine, endLine: j + 1 };
              }
            }
          }
        }
      }
    }

    return null;
  }

  /**
   * 生成重构建议 - 安全的分析策略
   */
  private generateRefactoringAdvice(
    content: string, 
    startLine: number, 
    endLine: number,
    methodName: string,
    nonEmptyLines: number
  ): string[] {
    const lines = content.split('\n');
    const advice: string[] = [];
    
    console.error(`[generateRefactoringAdvice] 分析方法 ${methodName}，行 ${startLine}-${endLine}`);
    
    // 基本建议
    advice.push(`• 方法包含 ${nonEmptyLines} 行非空代码，建议拆分为多个小方法`);
    
    // 分析可能的重构机会
    const calculationBlocks = this.analyzeCalculationBlocks(lines, startLine, endLine);
    if (calculationBlocks.length > 0) {
      advice.push(`• 发现 ${calculationBlocks.length} 个计算块，建议提取为独立的计算方法`);
      calculationBlocks.forEach((block, index) => {
        advice.push(`  - 计算块 ${index + 1}: 第 ${block.startLine}-${block.endLine} 行 (${block.description})`);
      });
    }
    
    const validationBlocks = this.analyzeValidationBlocks(lines, startLine, endLine);
    if (validationBlocks.length > 0) {
      advice.push(`• 发现 ${validationBlocks.length} 个验证块，建议提取为验证方法`);
      validationBlocks.forEach((block, index) => {
        advice.push(`  - 验证块 ${index + 1}: 第 ${block.startLine}-${block.endLine} 行 (${block.description})`);
      });
    }
    
    const loggingBlocks = this.analyzeLoggingBlocks(lines, startLine, endLine);
    if (loggingBlocks.length > 0) {
      advice.push(`• 发现 ${loggingBlocks.length} 个日志块，建议提取为日志方法`);
    }
    
    // 通用建议
    advice.push(`• 建议使用 extract_method 工具手动提取特定代码段`);
    advice.push(`• 建议按业务逻辑将方法拆分为：验证、计算、处理、日志等独立方法`);
    
    return advice;
  }
  
  /**
   * 分析计算相关的代码块 - 仅分析不提取
   */
  private analyzeCalculationBlocks(lines: string[], startLine: number, endLine: number): Array<{ startLine: number, endLine: number, description: string }> {
    const blocks: Array<{ startLine: number, endLine: number, description: string }> = [];
    let blockStart = -1;
    let inCalculation = false;
    
    for (let i = startLine; i < endLine; i++) {
      const line = lines[i]?.trim() || '';
      
      if (!inCalculation && this.isCalculationStart(line)) {
        blockStart = i + 1;
        inCalculation = true;
        continue;
      }
      
      if (inCalculation && (this.isCalculationEnd(line) || this.isControlFlow(line) || i === endLine - 1)) {
        const blockEnd = i;
        if (blockEnd - blockStart >= 3) {
          blocks.push({
            startLine: blockStart,
            endLine: blockEnd,
            description: this.describeCalculationBlock(lines, blockStart, blockEnd)
          });
        }
        inCalculation = false;
      }
    }
    
    return blocks;
  }
  
  /**
   * 分析验证相关的代码块 - 仅分析不提取
   */
  private analyzeValidationBlocks(lines: string[], startLine: number, endLine: number): Array<{ startLine: number, endLine: number, description: string }> {
    const blocks: Array<{ startLine: number, endLine: number, description: string }> = [];
    let blockStart = -1;
    let consecutiveValidations = 0;
    
    for (let i = startLine; i < endLine; i++) {
      const line = lines[i]?.trim() || '';
      
      if (this.isValidation(line)) {
        if (blockStart === -1) {
          blockStart = i + 1;
        }
        consecutiveValidations++;
      } else if (blockStart > 0 && consecutiveValidations >= 3) {
        blocks.push({
          startLine: blockStart,
          endLine: i,
          description: `包含 ${consecutiveValidations} 个验证条件`
        });
        blockStart = -1;
        consecutiveValidations = 0;
      } else {
        blockStart = -1;
        consecutiveValidations = 0;
      }
    }
    
    return blocks;
  }
  
  /**
   * 分析日志记录代码块 - 仅分析不提取
   */
  private analyzeLoggingBlocks(lines: string[], startLine: number, endLine: number): Array<{ startLine: number, endLine: number, description: string }> {
    const blocks: Array<{ startLine: number, endLine: number, description: string }> = [];
    let blockStart = -1;
    let loggingLines = 0;
    
    for (let i = startLine; i < endLine; i++) {
      const line = lines[i]?.trim() || '';
      
      if (this.isLogging(line)) {
        if (blockStart === -1) {
          blockStart = i + 1;
        }
        loggingLines++;
      } else if (blockStart > 0 && loggingLines >= 2) {
        blocks.push({
          startLine: blockStart,
          endLine: i,
          description: `包含 ${loggingLines} 行日志代码`
        });
        blockStart = -1;
        loggingLines = 0;
      } else if (!line.startsWith('//') && line.length > 0) {
        blockStart = -1;
        loggingLines = 0;
      }
    }
    
    return blocks;
  }
  
  private describeCalculationBlock(lines: string[], startLine: number, endLine: number): string {
    const blockLines = lines.slice(startLine - 1, endLine);
    const content = blockLines.join(' ').toLowerCase();
    
    if (content.includes('price') || content.includes('价格')) return '价格计算';
    if (content.includes('discount') || content.includes('折扣')) return '折扣计算';
    if (content.includes('tax') || content.includes('税')) return '税费计算';
    if (content.includes('fee') || content.includes('费用')) return '费用计算';
    if (content.includes('total') || content.includes('总')) return '总计计算';
    return '数值计算';
  }
  
  // 辅助方法
  private isCalculationStart(line: string): boolean {
    return line.includes('// 计算') || line.includes('// 价格') || line.includes('// 费用') || line.includes('BigDecimal');
  }
  
  private isCalculationEnd(line: string): boolean {
    return line.includes('// ') && !line.includes('计算') && !line.includes('价格') && !line.includes('费用');
  }
  
  private isControlFlow(line: string): boolean {
    return line.startsWith('if ') || line.startsWith('for ') || line.startsWith('while ') || line.startsWith('try ') || line.startsWith('catch ');
  }
  
  private isValidation(line: string): boolean {
    return (line.startsWith('if ') && (line.includes('== null') || line.includes('!= null') || line.includes('.isEmpty()') || line.includes('.trim()') || line.includes('< ') || line.includes('> '))) ||
           line.includes('throw new');
  }
  
  private isLogging(line: string): boolean {
    return line.includes('logService.') || line.includes('System.out.') || line.includes('.log(') || line.includes('logger.');
  }
  
  private capitalizeFirst(str: string): string {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }

  /**
   * 检查是否是有效的Java类型
   */
  private isValidJavaType(type: string): boolean {
    if (!type || type.trim() === '') return false;
    
    const validTypes = [
      'void', 'boolean', 'byte', 'short', 'int', 'long', 'float', 'double', 'char',
      'String', 'Object', 'List', 'Map', 'Set', 'Collection', 'Date', 'BigDecimal',
      'Integer', 'Long', 'Double', 'Boolean', 'Character'
    ];
    
    // 检查基本类型
    if (validTypes.includes(type)) return true;
    
    // 检查泛型类型（如 List<String>）
    if (type.includes('<') && type.includes('>')) {
      const baseType = type.split('<')[0];
      return validTypes.includes(baseType);
    }
    
    // 检查数组类型（如 String[]）
    if (type.endsWith('[]')) {
      const baseType = type.substring(0, type.length - 2);
      return this.isValidJavaType(baseType);
    }
    
    // 检查是否看起来像类名（首字母大写）
    return /^[A-Z][a-zA-Z0-9_]*$/.test(type);
  }

  /**
   * 清理和格式化代码
   */
  private cleanAndFormatCode(code: string): string {
    const lines = code.split('\n');
    const cleanedLines: string[] = [];
    
    for (const line of lines) {
      // 移除多余的空白行
      if (line.trim() === '' && cleanedLines[cleanedLines.length - 1]?.trim() === '') {
        continue;
      }
      
      // 确保正确的缩进
      const trimmedLine = line.trim();
      if (trimmedLine !== '') {
        cleanedLines.push('        ' + trimmedLine);
      } else {
        cleanedLines.push('');
      }
    }
    
    // 移除开头和结尾的空行
    while (cleanedLines.length > 0 && cleanedLines[0].trim() === '') {
      cleanedLines.shift();
    }
    while (cleanedLines.length > 0 && cleanedLines[cleanedLines.length - 1].trim() === '') {
      cleanedLines.pop();
    }
    
    return cleanedLines.join('\n');
  }

  /**
   * 准备替换内容 - 完全重写版本
   */
  private prepareReplacement(
    methodName: string, 
    analysis: {
      parameters: string[],
      returnValue?: string,
      parameterTypes: Map<string, string>,
      declaredVariables: Map<string, string>,
      usedVariablesAfter: Set<string>,
      needToReturnVars: Set<string>
    },
    extractedCode: string
  ): string[] {
    const replacement: string[] = [];
    const extractedLines = extractedCode.split('\n');
    
    // 1. 保留在提取代码中声明但在后面还需要使用的变量声明
    for (const [varName, varType] of analysis.declaredVariables) {
      if (analysis.usedVariablesAfter.has(varName)) {
        // 检查是否是简单声明（没有初始化值）
        let isSimpleDeclaration = false;
        for (const line of extractedLines) {
          if (line.trim() === `${varType} ${varName};`) {
            isSimpleDeclaration = true;
            break;
          }
        }
        // 如果不是简单声明，需要保留变量声明
        if (!isSimpleDeclaration) {
          replacement.push(`        ${varType} ${varName};`);
        }
      }
    }
    
    // 2. 生成方法调用
    const params = analysis.parameters.join(', ');
    
    if (analysis.needToReturnVars.size > 0) {
      // 如果有变量需要返回，接收返回值
      const firstVar = Array.from(analysis.needToReturnVars)[0];
      replacement.push(`        ${firstVar} = ${methodName}(${params});`);
    } else if (analysis.returnValue && analysis.returnValue !== 'void') {
      // 如果方法本身有返回值
      replacement.push(`        return ${methodName}(${params});`);
    } else {
      // 普通方法调用
      replacement.push(`        ${methodName}(${params});`);
    }
    
    return replacement;
  }

  /**
   * 查找成员变量
   */
  private findMemberFields(content: string): Map<string, string> {
    const memberFields = new Map<string, string>();
    const lines = content.split('\n');
    
    // 查找类声明
    let inClass = false;
    let braceCount = 0;
    
    for (const line of lines) {
      const trimmed = line.trim();
      
      // 跳过注释
      if (trimmed.startsWith('//') || trimmed.startsWith('/*')) {
        continue;
      }
      
      // 检查类开始
      if (trimmed.includes('class ') && trimmed.includes('{')) {
        inClass = true;
        braceCount = 1;
        continue;
      }
      
      // 计算大括号
      if (inClass) {
        for (const char of line) {
          if (char === '{') braceCount++;
          else if (char === '}') {
            braceCount--;
            if (braceCount === 0) {
              inClass = false;
              break;
            }
          }
        }
      }
      
      // 在类内部且在方法外部
      if (inClass && braceCount === 1) {
        // 匹配成员变量声明，包括注解的情况
        const patterns = [
          /^\s*(?:@\w+\s*)*\s*(?:private|protected|public)?\s*(?:static)?\s*(?:final)?\s*(\w+(?:<[^>]*>)?)\s+(\w+)\s*[=;]/,
          /^\s*(?:@Autowired|@Resource|@Inject)\s*(?:\([^)]*\))?\s*(?:private|protected|public)?\s*(\w+(?:<[^>]*>)?)\s+(\w+)\s*;/
        ];
        
        for (const pattern of patterns) {
          const match = pattern.exec(trimmed);
          if (match) {
            const fieldType = match[1];
            const fieldName = match[2];
            if (!this.isJavaKeywordOrBuiltin(fieldType)) {
              memberFields.set(fieldName, fieldType);
            }
            break;
          }
        }
      }
    }
    
    return memberFields;
  }

  /**
   * 判断是否是方法结束
   */
  private isMethodEnd(lines: string[], index: number): boolean {
    let braceCount = 0;
    let foundMethodStart = false;
    
    // 向上查找方法开始
    for (let i = index; i >= 0; i--) {
      const line = lines[i];
      for (const char of line) {
        if (char === '}') {
          braceCount++;
        } else if (char === '{') {
          braceCount--;
          if (braceCount < 0) {
            foundMethodStart = true;
            break;
          }
        }
      }
      
      if (foundMethodStart && braceCount === 0) {
        return true;
      }
    }
    
    return false;
  }

  /**
   * 移除字符串内容以避免括号计数错误
   */
  private removeStringContent(line: string): string {
    // 移除双引号字符串
    let result = line.replace(/"[^"]*"/g, '""');
    // 移除单引号字符串
    result = result.replace(/'[^']*'/g, "''");
    // 移除注释
    const commentIndex = result.indexOf('//');
    if (commentIndex !== -1) {
      result = result.substring(0, commentIndex);
    }
    return result;
  }
}